const { v4: uuidv4 } = require('uuid');
const fs = require('fs');
const path = require('path');
const config = require('../config');
const axios = require('axios');

// 模拟数据库
const TRADES_FILE = path.join(__dirname, '../data/trades.json');
const POSITIONS_FILE = path.join(__dirname, '../data/positions.json');
const ORDERS_FILE = path.join(__dirname, '../data/orders.json');

// 确保数据目录存在
const ensureDataDirExists = () => {
  const dataDir = path.join(__dirname, '../data');
  if (!fs.existsSync(dataDir)) {
    fs.mkdirSync(dataDir);
  }
};

// 初始化交易数据
const initTrades = () => {
  ensureDataDirExists();
  if (!fs.existsSync(TRADES_FILE)) {
    fs.writeFileSync(TRADES_FILE, JSON.stringify([]));
  }
};

// 初始化持仓数据
const initPositions = () => {
  ensureDataDirExists();
  if (!fs.existsSync(POSITIONS_FILE)) {
    fs.writeFileSync(POSITIONS_FILE, JSON.stringify([]));
  }
};

// 初始化订单数据
const initOrders = () => {
  ensureDataDirExists();
  if (!fs.existsSync(ORDERS_FILE)) {
    fs.writeFileSync(ORDERS_FILE, JSON.stringify([]));
  }
};

// 获取交易记录
exports.getTrades = (filters = {}) => {
  initTrades();
  let trades = JSON.parse(fs.readFileSync(TRADES_FILE, 'utf8'));

  // 应用过滤条件
  if (filters.symbol) {
    trades = trades.filter(trade => trade.symbol === filters.symbol);
  }
  if (filters.startTime) {
    trades = trades.filter(trade => new Date(trade.timestamp) >= new Date(filters.startTime));
  }
  if (filters.endTime) {
    trades = trades.filter(trade => new Date(trade.timestamp) <= new Date(filters.endTime));
  }

  // 按时间倒序排列
  return trades.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
};

// 获取当前持仓
exports.getPositions = () => {
  initPositions();
  return JSON.parse(fs.readFileSync(POSITIONS_FILE, 'utf8'));
};

// 保存持仓
exports.savePosition = (position) => {
  initPositions();
  let positions = JSON.parse(fs.readFileSync(POSITIONS_FILE, 'utf8'));
  const index = positions.findIndex(p => p.symbol === position.symbol);

  if (index !== -1) {
    // 更新现有持仓
    positions[index] = position;
  } else {
    // 添加新持仓
    positions.push(position);
  }

  fs.writeFileSync(POSITIONS_FILE, JSON.stringify(positions, null, 2));
  return position;
};

// 下单
exports.createOrder = async (orderData) => {
  initOrders();
  const orders = JSON.parse(fs.readFileSync(ORDERS_FILE, 'utf8'));

  // 模拟订单
  const newOrder = {
    id: uuidv4(),
    symbol: orderData.symbol,
    type: orderData.type || 'limit',
    side: orderData.side,
    price: orderData.price,
    quantity: orderData.quantity,
    status: 'filled', // pending, filled, canceled
    timestamp: new Date().toISOString(),
    filledPrice: orderData.price,
    filledQuantity: orderData.quantity,
    fee: (orderData.price * orderData.quantity * 0.001).toFixed(8) // 模拟手续费
  };

  // 保存订单
  orders.push(newOrder);
  fs.writeFileSync(ORDERS_FILE, JSON.stringify(orders, null, 2));

  // 记录交易
  const newTrade = {
    id: uuidv4(),
    orderId: newOrder.id,
    symbol: newOrder.symbol,
    side: newOrder.side,
    price: newOrder.filledPrice,
    quantity: newOrder.filledQuantity,
    fee: newOrder.fee,
    timestamp: new Date().toISOString()
  };

  initTrades();
  const trades = JSON.parse(fs.readFileSync(TRADES_FILE, 'utf8'));
  trades.push(newTrade);
  fs.writeFileSync(TRADES_FILE, JSON.stringify(trades, null, 2));

  // 更新持仓
  const positions = exports.getPositions();
  const positionIndex = positions.findIndex(p => p.symbol === newOrder.symbol);

  if (positionIndex !== -1) {
    // 更新现有持仓
    const position = positions[positionIndex];
    if (newOrder.side === 'buy') {
      position.quantity += parseFloat(newOrder.filledQuantity);
      position.avgPrice = (
        (position.avgPrice * position.quantity + parseFloat(newOrder.filledPrice) * parseFloat(newOrder.filledQuantity)) /
        (position.quantity + parseFloat(newOrder.filledQuantity))
      ).toFixed(8);
    } else if (newOrder.side === 'sell') {
      position.quantity -= parseFloat(newOrder.filledQuantity);
      // 如果持仓为0，则移除该持仓
      if (position.quantity <= 0) {
        positions.splice(positionIndex, 1);
        fs.writeFileSync(POSITIONS_FILE, JSON.stringify(positions, null, 2));
        return newOrder;
      }
    }
    fs.writeFileSync(POSITIONS_FILE, JSON.stringify(positions, null, 2));
  } else if (newOrder.side === 'buy') {
    // 添加新持仓
    const newPosition = {
      symbol: newOrder.symbol,
      quantity: parseFloat(newOrder.filledQuantity),
      avgPrice: parseFloat(newOrder.filledPrice),
      timestamp: new Date().toISOString()
    };
    positions.push(newPosition);
    fs.writeFileSync(POSITIONS_FILE, JSON.stringify(positions, null, 2));
  }

  return newOrder;
};

// 取消订单
exports.cancelOrder = (id) => {
  initOrders();
  let orders = JSON.parse(fs.readFileSync(ORDERS_FILE, 'utf8'));
  const index = orders.findIndex(order => order.id === id);

  if (index === -1) {
    return { success: false, message: '订单不存在' };
  }

  // 只能取消未成交的订单
  if (orders[index].status !== 'pending') {
    return { success: false, message: '只能取消未成交的订单' };
  }

  // 更新订单状态为已取消
  orders[index].status = 'canceled';
  fs.writeFileSync(ORDERS_FILE, JSON.stringify(orders, null, 2));

  return { success: true, message: '订单已取消' };
};

// 获取订单详情
exports.getOrderById = (id) => {
  initOrders();
  const orders = JSON.parse(fs.readFileSync(ORDERS_FILE, 'utf8'));
  return orders.find(order => order.id === id);
};

// 获取订单列表
exports.getOrders = (filters = {}) => {
  initOrders();
  let orders = JSON.parse(fs.readFileSync(ORDERS_FILE, 'utf8'));

  // 应用过滤条件
  if (filters.symbol) {
    orders = orders.filter(order => order.symbol === filters.symbol);
  }
  if (filters.status) {
    orders = orders.filter(order => order.status === filters.status);
  }

  // 按时间倒序排列
  return orders.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
};